package com.study.redis.article.controller;

import com.alibaba.fastjson.JSON;
import com.study.redis.article.domain.Article;
import com.study.redis.article.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by hegy on 2018/6/4.
 */
@Controller
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;


    @PostMapping("list")
    @ResponseBody
    public String listArticle(HttpServletRequest request, String type){
        List<Article> list = articleService.listArticle(type);
        return  JSON.toJSONString(list);
    }

    @PostMapping("add")
    @ResponseBody
    public String addArticle(Article article){
        articleService.addArticle(article);
        return "ok";
    }

    @PostMapping("del")
    @ResponseBody
    public String delArticle(String artId){
        boolean result = articleService.delArticle(artId);
        if (result) {
            return "删除成功";
        } else {
            return "删除失败";
        }
    }

    @PostMapping("vote")
    @ResponseBody
    public String voteArticle(HttpServletRequest request, String artId) {
        HttpSession session = request.getSession();
        Integer userId = (Integer)session.getAttribute("userId");
        boolean result = articleService.voteArticle(artId, userId);
        if (result) {
            return "投票成功";
        } else {
            return "该文章已停止投票或您已经投过该文章";
        }
    }
}
